package com.mz.ieann.dokit.utils

import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.Response
import okio.BufferedSink
import okio.Sink
import okio.buffer
import okio.sink
import java.io.File
import java.io.IOException

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 文件下载于上传
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/6/1
 */
object FileHttpUtil {

    private const val TAG = "http_util"

    /**
     * 文件下载
     * @param url 文件地址
     * @param path 保存路径
     */
    @JvmStatic
    fun download(
        url: String,
        path: String,
        listener: FileDownUtilListener? = null
    ){
        Log.v(TAG, "download, url:$url")
        Log.v(TAG, "download, path:$path")
        OkHttpClient().newCall(
            Request.Builder().url(url).build()
        ).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                var sink: Sink? = null
                var buffer: BufferedSink? = null
                try {
                    val dirFile = File(path.substring(0, path.lastIndexOf("/")))
                    if (!dirFile.exists()){
                        dirFile.mkdirs()
                    }
                    val file = File(path)
                    if (file.exists()){
                        file.delete()
                    }
                    val createResult = file.createNewFile()
                    Log.v(TAG, "download, createResult:$createResult")
                    sink = file.sink()
                    buffer = sink.buffer()
                    buffer.writeAll(response.body?.source()!!)

                    listener?.downSuccess()
                }catch (e: Exception){
                    Log.e(TAG, "download file save fail, error:$e")
                }finally {
                    buffer?.close()
                    sink?.close()
                }
            }
            override fun onFailure(call: Call, e: IOException) {
                Log.e(TAG, "download file fail, error:$e")
            }
        })
    }

    /**
     * 文件上传
     * @param url 上传地址
     * @param path 保存路径
     */
    @JvmStatic
    fun upload(
        url: String,
        path: String
    ){
        Log.v(TAG, "upload, url:$url")
        Log.v(TAG, "upload, path:$path")
        val file = File(path)
        val client = OkHttpClient()
        val body: RequestBody = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            // 提交普通字段
            .addFormDataPart("id", "")
            // 提交文件，第一个参数时键，第二个参数是文件名，第三个参数是requestBody
            .addFormDataPart(
                "file",
                file.name,
                file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            )
            .build()
        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                Log.v(TAG, "upload file success")
            }
            override fun onFailure(call: Call, e: IOException) {
                Log.v(TAG, "upload file fail, error:$e")
            }
        })
    }

    /**
     * 下载图片成功回调
     */
    interface FileDownUtilListener{
        fun downSuccess()
    }

}